<?php

namespace App\Admin\Controllers;

use App\Models\Credit;
use DB;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;

class CreditController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('信用管理');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('新增');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Credit::class, function (Grid $grid) {
            $grid->actions(function ($actions) {
                $actions->disableView();
            });
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->id('ID')->sortable();
            $grid->column('module','类别')->using(config('options.credit_module'));
            $grid->target_id('名称')->display(function ($val){
                $data = DB::table($this->module)->find((int)$val);
                return $data?($this->module=='guides'?$data->name:$data->title):'';
            });
            $grid->column('date','时间')->display(function ($val){
                return $this->year.'-'.$this->month;
            });
            $grid->status('状态')->using(config('options.credit_status'));
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Credit::class, function (Form $form) {
            $form->select('module', '类别')->options(config('options.credit_module'))->load('target_id','/api/target_id');
            $form->select('target_id', '选项')->options(function ($val){
                $data = DB::table($this->module)->find($val);
                return $this->module=='guides'?[$data->id=>$data->name]:[$data->id=>$data->title];
            });
            $form->number('reduce', '扣分')->max(100);
            $form->year('year','年份');
            $form->month('month', '月份');
            $form->radio('status','审核')->options(config('options.credit_status'));
        });
    }
}
